﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Microsoft.Win32;
using System.Text.RegularExpressions;

namespace FIS.iDET
{
    public partial class LicenseKeyForm : Form
    {
        public LicenseKeyForm()
        {
            InitializeComponent();
        }

        private void LicenseKeyForm_Load(object sender, EventArgs e)
        {
            textBoxMachineID.Text = LicenseService.GetMachineID();
        }

        private void buttonExit_Click(object sender, EventArgs e)
        {
            Application.ExitThread();
        }

        private void buttonActivate_Click(object sender, EventArgs e)
        {
            string serialToCheck = textBoxLicenseKey.Text.Trim().ToUpper();
            
            if (LicenseService.IsSerialNumberCorrect(serialToCheck))
            {
                // activation succeeds
                // informs user
                MessageBox.Show("Activation succeeds! Application will now close, please re-open application to start using it.", "Activation succeeds", MessageBoxButtons.OK, MessageBoxIcon.Information);
                
                // add valid serial number to registry
                RegistryService.SetValue(GlobalConstants.REGISTRY_SERIAL_NUMBER_KEY, serialToCheck);

                // add user name to registry
                RegistryService.SetValue(GlobalConstants.REGISTRY_USER_NAME, textBoxUserName.Text);
                
                // exit app to finish activation                                               
                Application.ExitThread();
            }
            else
            {
                // activation fails
                MessageBox.Show("Wrong serial number!", "Activation fails", MessageBoxButtons.OK, MessageBoxIcon.Error);
                
                textBoxLicenseKey.Focus();
            }
        }

        private void textBoxLicenseKey_TextChanged(object sender, EventArgs e)
        {
            // check if serial number form is valid
            string serial = textBoxLicenseKey.Text.Trim().ToUpper();

            Match match = Regex.Match(
                serial,
                @"[A-F0-9]{4}-[A-F0-9]{4}-[A-F0-9]{4}-[A-F0-9]{4}-[A-F0-9]{4}-[A-F0-9]{4}-[A-F0-9]{4}-[A-F0-9]{4}"
            );

            // change activate button status due to validation of user input's serial number
            labelActivate.Enabled = match.Success;
        }
    }
}
